package com.quick.job;

import com.google.common.collect.Lists;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @ClassName JobBeanTest
 * @Description TODO
 * @Author wangxin332
 * @Date 2018/10/19 上午11:36
 * @Version 1.0
 **/
@Component
public class JobBeanTest {
	public void handler() throws Exception{
		/**
		 * 创建线程池
		 */
		ExecutorService executorService = Executors.newCachedThreadPool();
		List<Future<String>> resultList = Lists.newArrayList();
		for (int i = 0; i <10 ; i++) {
			resultList.add(executorService.submit(new JobBeanTest.TestWorker(i)));
		}
		/**
		 * 阻止新任务的提交，但是原本已经提交的，不会受到影响，当已提交的任务全部完成后，中断闲置的线程
		 */
		executorService.shutdown();
		executorService.awaitTermination(10, TimeUnit.DAYS);
		/**
		 * 获取返回的值
		 */
		List<String> values = Lists.newArrayList();
		for (Future<String> aList : resultList) {
			//判断任务是否完成
			if (aList.isDone()) {
				values.add(aList.get());
			}
		}

		for (String item : values) {
			System.out.println(item);
		}
		System.out.println("JobBeanTest--end");
	}


	/**
	 * https://www.jianshu.com/p/cfda708a3478
	 * @throws Exception
	 */
	public void handlerTwo() throws Exception{
		/**
		 * 创建线程池
		 */
		ExecutorService executorService = Executors.newCachedThreadPool();
		CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
		for (int i = 0; i <10 ; i++) {
			completionService.submit(new JobBeanTest.TestWorker(i));
		}
		/**
		 * 阻止新任务的提交，但是原本已经提交的，不会受到影响，当已提交的任务全部完成后，中断闲置的线程
		 */
		executorService.shutdown();
		executorService.awaitTermination(10, TimeUnit.DAYS);
		int i=0;
		while (i<10){
			Future<String> future = completionService.take();
			if (null==future){
				continue;
			}
			System.out.println(future.get());
			i++;
		}
	}
	private static class TestWorker implements Callable<String> {
		private int a;
		public TestWorker (int a){
			this.a = a;
		}

		@Override
		public String call() throws Exception {
			return "Test:"+a;
		}
	}
}
